package com.reading.core.manager.system.impl;

import com.reading.common.cache.service.CacheService;
import com.reading.common.constant.UserConstants;
import com.reading.common.entity.system.Menu;
import com.reading.common.entity.system.Role;
import com.reading.common.persistence.system.MenuMapper;
import com.reading.common.persistence.system.RoleMenuMapper;
import com.reading.common.utils.StringUtil;
import com.reading.core.manager.system.IMenuManager;
import com.reading.core.utils.TreeUtil;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.text.MessageFormat;
import java.util.*;

/**
 * 菜单 业务层处理
 *
 * @author ruoyi
 */
@Service("menuService")
public class MenuManagerImpl implements IMenuManager {

    private static final String PREMISSION_STRING = "perms[\"{0}\"]";

    @Resource
    private MenuMapper menuMapper;

    @Resource
    private RoleMenuMapper roleMenuMapper;

    @Resource
    private CacheService cacheService;

    /**
     * 根据用户ID查询菜单
     *
     * @param userId 用户ID
     * @return 菜单列表
     */
    @Override
    public List<Menu> selectMenusByUserId(Integer userId) {
        List<Menu> menus = menuMapper.selectMenusByUserId(userId);
        return TreeUtil.getChildPerms(menus, 0);
    }

    /**
     * 查询菜单集合
     *
     * @return 所有菜单信息
     */
    @Override
    public List<Menu> selectMenuAll() {
        return menuMapper.selectMenuAll();
    }

    /**
     * 根据用户ID查询权限
     *
     * @param userId 用户ID
     * @return 权限列表
     */
    @Override
    public Set<String> selectPermsByUserId(Integer userId) {
        Set<String> permsSet = cacheService.selectPerms(userId);
        if (permsSet == null || permsSet.size() == 0) {
            permsSet = new HashSet<>();
            List<String> perms = menuMapper.selectPermsByUserId(userId);
            for (String perm : perms) {
                if (StringUtil.isNotEmpty(perm)) {
                    permsSet.addAll(Arrays.asList(perm.trim().split(",")));
                }
            }
            cacheService.addAllPerms(userId, permsSet);
        }
        return permsSet;
    }

    /**
     * 根据角色ID查询菜单
     *
     * @param role 角色对象
     * @return 菜单列表
     */
    @Override
    public List<Map<String, Object>> roleMenuTreeData(Role role) {
        Integer roleId = role.getRoleId();
        List<Map<String, Object>> trees = new ArrayList<>();
        List<Menu> menuList = menuMapper.selectMenuAll();
        if (StringUtil.isNotNull(roleId)) {
            List<String> roleMenuList = menuMapper.selectMenuTree(roleId);
            trees = getTrees(menuList, true, roleMenuList, true);
        } else {
            trees = getTrees(menuList, false, null, true);
        }
        return trees;
    }

    /**
     * 查询所有菜单
     *
     * @return 菜单列表
     */
    @Override
    public List<Map<String, Object>> menuTreeData() {
        List<Menu> menuList = menuMapper.selectMenuAll();
        return getTrees(menuList, false, null, false);
    }

    /**
     * 查询系统所有权限
     *
     * @return 权限列表
     */
    @Override
    public LinkedHashMap<String, String> selectPermsAll() {
        LinkedHashMap<String, String> section = new LinkedHashMap<>();
        List<Menu> permissions = menuMapper.selectMenuAll();
        if (StringUtil.isNotEmpty(permissions)) {
            for (Menu menu : permissions) {
                section.put(menu.getUrl(), MessageFormat.format(PREMISSION_STRING, menu.getPerms()));
            }
        }
        return section;
    }

    /**
     * 对象转菜单树
     *
     * @param menuList 菜单列表
     * @param isCheck 是否需要选中
     * @param roleMenuList 角色已存在菜单列表
     * @param permsFlag 是否需要显示权限标识
     */
    public List<Map<String, Object>> getTrees(List<Menu> menuList, boolean isCheck, List<String> roleMenuList,
                                              boolean permsFlag) {
        List<Map<String, Object>> trees = new ArrayList<>();
        for (Menu menu : menuList) {
            Map<String, Object> deptMap = new HashMap<>();
            deptMap.put("id", menu.getMenuId());
            deptMap.put("pId", menu.getParentId());
            deptMap.put("name", transMenuName(menu, roleMenuList, permsFlag));
            deptMap.put("title", menu.getMenuName());
            if (isCheck) {
                deptMap.put("checked", roleMenuList.contains(menu.getMenuId() + menu.getPerms()));
            } else {
                deptMap.put("checked", false);
            }
            trees.add(deptMap);
        }
        return trees;
    }

    public String transMenuName(Menu menu, List<String> roleMenuList, boolean permsFlag) {
        StringBuilder sb = new StringBuilder();
        sb.append(menu.getMenuName());
        if (permsFlag) {
            sb.append("<font color=\"#888\">&nbsp;&nbsp;&nbsp;").append(menu.getPerms()).append("</font>");
        }
        return sb.toString();
    }

    /**
     * 删除菜单管理信息
     *
     * @param menuId 菜单ID
     * @return 结果
     */
    @Override
    public int deleteMenuById(Integer menuId) {
        return menuMapper.deleteMenuById(menuId);
    }

    /**
     * 根据菜单ID查询信息
     *
     * @param menuId 菜单ID
     * @return 菜单信息
     */
    @Override
    public Menu selectMenuById(Integer menuId) {
        return menuMapper.selectMenuById(menuId);
    }

    /**
     * 查询子菜单数量
     *
     * @param parentId 菜单ID
     * @return 结果
     */
    @Override
    public int selectCountMenuByParentId(Integer parentId) {
        return menuMapper.selectCountMenuByParentId(parentId);
    }

    /**
     * 查询菜单使用数量
     *
     * @param menuId 菜单ID
     * @return 结果
     */
    @Override
    public int selectCountRoleMenuByMenuId(Integer menuId) {
        return roleMenuMapper.selectCountRoleMenuByMenuId(menuId);
    }

    /**
     * 保存菜单信息
     *
     * @param menu 菜单信息
     * @return 结果
     */
    @Override
    public int saveMenu(Menu menu) {
        Integer menuId = menu.getMenuId();
        if (StringUtil.isNotNull(menuId)) {
            return menuMapper.updateMenu(menu);
        } else {
            return menuMapper.insertMenu(menu);
        }
    }

    /**
     * 校验菜单名称是否唯一
     *
     * @param menu 菜单信息
     * @return 结果
     */
    @Override
    public String checkMenuNameUnique(Menu menu) {
        if (menu.getMenuId() == null) {
            menu.setMenuId(-1);
        }
        Integer menuId = menu.getMenuId();
        Menu info = menuMapper.checkMenuNameUnique(menu.getMenuName());
        if (StringUtil.isNotNull(info) && StringUtil.isNotNull(info.getMenuId())
            && !info.getMenuId().equals(menuId)) {
            return UserConstants.MENU_NAME_NOT_UNIQUE;
        }
        return UserConstants.MENU_NAME_UNIQUE;
    }

}
